import { defineStore } from 'pinia'
import { ref } from 'vue'
import { nanoid } from 'nanoid'
import SockJS from 'sockjs-client'
import { Client } from '@stomp/stompjs'
import { useUserStore } from '@/stores/user.ts'

interface ChatMessage {
  messageId: string
  senderId: string|number|null|undefined
  receiverId: string
  content: string
  status: number
  timestamp: number
  isMine: boolean
  messageType?: number  // 必填字段，消息类型（1文本/2图片/5文件等）
  attachments?: Array<{  // 将files改为attachments
    url: string
    name: string
    size: number
    type: string
  }>
}

export const useChatStore = defineStore('chat', () => {
  const socket = ref<WebSocket | null>(null)
  const stompClient = ref<Client | null>(null)
  const messages = ref<ChatMessage[]>([])
  const currentChat = ref<string | null|number>(null)
  const unreadCount = ref(0)
  const connectionStatus = ref<'connecting' | 'connected' | 'disconnected'>('disconnected')
  const retryCount = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(20)
  const hasMore = ref(true)

  const initConnection = () => {
    if (stompClient.value?.connected) return

    const token = localStorage.getItem('token')
    const url = `http://[2409:8a4c:832:c590::36b]:8081/wsSockjs?token=${token}`

    // 初始化STOMP客户端
    stompClient.value = new Client({
      webSocketFactory: () => new SockJS(url),
      reconnectDelay: 5000,
      heartbeatIncoming: 4000,
      heartbeatOutgoing: 4000,
      onConnect: () => {
        console.log('STOMP连接成功')
        connectionStatus.value = 'connected'
        retryCount.value = 0
        resendPendingMessages()

        // 订阅私有消息队列
        stompClient.value?.subscribe(`/${userInfo.userInfo?.userId}/queue/private`, message => {
          console.log("接收消息"+message.body)
          handleIncomingMessage(JSON.parse(message.body))
        })
        stompClient.value?.subscribe(`/user/${userInfo.userInfo?.userId}/queue/private`, message => {
          console.log("接收消息"+message.body)
          handleIncomingMessage(JSON.parse(message.body))
        })
      },
      onStompError: frame => {
        console.error('STOMP协议错误:', frame.headers.message)
        handleReconnection(userInfo.userInfo?.userId)
      }
    })

    stompClient.value.activate()
  }
  const userInfo = useUserStore()
  const sendMessage = async (content: string, receiverId: string, files: any) => {
    // 处理附件数据
    let attachments=[]
    console.log('--')
    console.log(files)
    if (files&&files.length > 0) {
        attachments = files.map(file => {
        const responseData = file.response?.data || file.url; // 兼容两种数据结构
        return {
          fileName: file.name,
          fileUrl: responseData,
          fileType: getFileType(responseData), // 新增文件类型判断方法
          fileSize: Number(file.size)
        };
      });
    }

    const messageId = nanoid()
    const newMsg: ChatMessage = {
      messageId: messageId,
      senderId: userInfo.userInfo?.userId,
      receiverId,
      content,
      status: 0 as any,
      timestamp: Date.now(),
      isMine: true,
      attachments,
      messageType: attachments.length>0 ? 2 : 1,
    }

    messages.value.push(newMsg)
    try {
      const message = {
        type:'PRIVATE_MESSAGE',
        chatType: 1,
        receiverId: Number(receiverId),
        senderId: userInfo.userInfo?.userId,
        content,
        messageType: newMsg.messageType,
        attachments: files
      }

      if (stompClient.value?.connected) {
        stompClient.value.publish({
          destination: '/app/chat.private',
          body: JSON.stringify(message)
        })
        newMsg.status = 1
      } else {
        storeOfflineMessage(message)
        newMsg.status = 3
      }
    } catch (error) {
      console.error('消息发送失败:', error)
      newMsg.status = 4
    }
  }
  const isVisible = ref(false)
  const handleIncomingMessage = (msg: any) => {
    console.log("接收消息")
    const existing = messages.value.find(m => m.messageId === msg.messageId)
    if (!existing) {
      const baseMessage = {
        messageId: msg.messageId,
        senderId: String(msg.senderId),
        receiverId: String(msg.receiverId),
        content: msg.content,
        status: msg.status,
        messageType: msg.messageType,  // 新增messageType
        timestamp: msg.timestamp,      // 直接使用原始timestamp数组
        isMine: false,
      }
      // 添加附件处理逻辑
      if (msg.messageType !== 1 && msg.attachments) {
        messages.value.push({
          ...baseMessage,
          attachments: msg.attachments.map((a: any) => ({
            fileUrl: a.fileUrl,
            fileName: a.fileName,
            fileSize: a.fileSize,
            fileType: a.fileType
          }))
        })
      }else {
        messages.value.push(baseMessage)
      }
      if (msg.status === 0) {
        unreadCount.value += 1
      }
      isVisible.value = isVisible.value?false:true
    }
  }
  const getFileType = (url: string) => {
    console.log(url)
    const extension = url.split('.').pop()?.toLowerCase();
    console.log(extension)
    if (['jpg','jpeg','png','gif'].includes(extension)) return 'image';
    if (['mp4','webm','ogg'].includes(extension)) return 'video';
    return extension || 'file';
  };
  // 改进的离线存储
  const storeOfflineMessage = (msg: any) => {
    try {
      const stored = localStorage.getItem('offlineMessages') || '[]'
      const messages = JSON.parse(stored)
      messages.push({ ...msg, retries: 0 })
      localStorage.setItem('offlineMessages', JSON.stringify(messages))
    } catch (error) {
      console.error('离线存储失败:', error)
    }
  }

  // 自动重发机制
  const resendPendingMessages = () => {
    const pendingMessages = messages.value.filter(
      m => m.status
    )
    pendingMessages.forEach(msg => {
      if (msg.status==4) msg.status
      sendMessage(msg.content, msg.receiverId,msg.attachments)
    })
  }

  // 智能重连机制
  const handleReconnection = (userId: any) => {
    const maxRetries = 5
    const baseDelay = 1000

    if (retryCount.value < maxRetries) {
      const delay = baseDelay * Math.pow(2, retryCount.value)
      retryCount.value++
      setTimeout(() => initConnection(), delay)
    }
  }
  const clearMessages=()=>{
    messages.value=[]
  }
  const updateMessages=(newMessage: any)=>{
    messages.value=newMessage
  }
  const updateMessagesMore=(newMessage: any)=>{
    console.log("=========")
    console.log(messages.value)
    messages.value = [...newMessage, ...messages.value];
    console.log(messages.value)
    console.log("=========11")
  }
  return {
    messages,
    currentChat,
    unreadCount,
    isVisible,
    connectionStatus,
    initConnection,
    updateMessages,
    updateMessagesMore,
    clearMessages,
    sendMessage,
    handleIncomingMessage
  }
})
